package com.voute.View.Activity;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Consts.Constants;
import com.voute.Presenter.IAppInitPresenter;
import com.voute.Presenter.Impl.AppInitPresenterImpl;
import com.voute.R;
import com.voute.Utils.DeviceUtils;
import com.voute.Utils.GlideUtils;
import com.voute.Utils.PreferenceUtils;
import com.voute.View.IView.ISplashView;
import com.zxinsight.MLink;
import com.zxinsight.mlink.MLinkCallback;
import com.zxinsight.mlink.MLinkIntentBuilder;

import java.util.Date;
import java.util.Map;

import static com.umeng.socialize.utils.DeviceConfig.context;

/**
 * 启动页
 * Created by liukanshan on 2017/1/11.
 */

public class SplashActivity extends BaseActivity implements ISplashView {

    private ImageView welcome_imv;

    private LocationManager locationManager;

    private long refernece;

    private String fileName = "";

    private MaterialDialog progressDialog;

    private BroadcastReceiver receiver;

    private IAppInitPresenter appInitPresenter;

    private String action = "";
    private String dataString = "";

    private Intent url_intent;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            com.orhanobut.logger.Logger.i("receive1");
            if (getIntent().getData() != null) {
                MLink.getInstance(SplashActivity.this).router(SplashActivity.this, getIntent().getData());
//                App.GetInstance().finishActivity(SplashActivity.this);
            } else {
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                SplashActivity.this.startActivity(intent);
//                App.GetInstance().finishActivity(SplashActivity.this);
            }
        }
    };

    @Override
    public void initAppInfo() {
        appInitPresenter.initApp();
    }

    @Override
    public void enterApp() {
        handler.sendEmptyMessageDelayed(0x01, 1000);
    }

    @Override
    public void exitApp() {
        this.unregisterReceiver(receiver);
        App.GetInstance().exit();
    }

    @Override
    public void showOptionalUpdateDialog(final String download_url) {
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("您有新的版本升级")
                .cancelable(false)
                .negativeText("取消")
                .positiveText("升级").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                updateApk(download_url);
            }
        }).onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                enterApp();
            }
        }).show();
    }

    @Override
    public void showForceUpdateDialog(final String download_url) {
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("您有新的版本升级")
                .cancelable(false)
                .positiveText("升级").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                updateApk(download_url);
            }
        }).show();
    }

    @Override
    public void updateApk(String downloadUri) {
        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(downloadUri);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        // 设置下载路径和文件名
        fileName = (new Date()).getTime() + "";
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, (fileName + ".apk"));
        request.setDescription("最新版apk下载");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType("application/vnd.android.package-archive");
        // 设置为可被媒体扫描器找到
        request.allowScanningByMediaScanner();
        // 设置为可见和可管理
        request.setVisibleInDownloadsUi(true);
        refernece = manager.enqueue(request);
        progressDialog = new MaterialDialog.Builder(this)
                .title("更新App")
                .content("正在下载请稍后")
                .progress(true, 0)
                .autoDismiss(false)
                .cancelable(false)
                .build();
        progressDialog.show();
    }

    @Override
    public void saveRSAPublicKey(String public_key) {
        PreferenceUtils.SaveRSAKey(public_key);
        Constants.setRsaKey(public_key);
    }

    @Override
    public void showWelcomeImage(String image_url) {
//        GlideUtils.getInstance().loadSimpleContextVitMap(this, image_url, welcome_imv);
        GlideUtils.getInstance().LoadContextBitmap(this, image_url, welcome_imv, R.mipmap.boot_default_bg, R.mipmap.boot_default_bg, GlideUtils.LOAD_BITMAP);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    public void setupView() {
        action = getIntent().getAction();
        dataString = getIntent().getDataString();
        welcome_imv = $(R.id.welcome_imv);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        url_intent = getIntent();
//        MLink.getInstance(this).registerWithAnnotation(this);
        MLink.getInstance(this).registerDefault(new MLinkCallback() {
            @Override
            public void execute(Map paramMap, Uri uri, Context context) {
                //默认的路由 如果没有匹配则转跳到 MainActivity 为你的首页
                MLinkIntentBuilder.buildIntent(paramMap, context, MainActivity.class);
            }
        });
        // fivesec_mw_feeds:  mLink 的 key, mLink的唯一标识,用于进行路由操作
        MLink.getInstance(context).register("fivesec_mw_feeds", new MLinkCallback() {
            public void execute(Map<String, String> paramMap, Uri uri, final Context context) {
//                MLinkIntentBuilder.buildIntent(paramMap, context, FeedDetailInfoActivity.class);
                Intent intent = new Intent(context, FeedDetailInfoActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                if (paramMap != null) {
                    for (Map.Entry<String, String> param : paramMap.entrySet()) {
                        intent.putExtra(param.getKey(), param.getValue());
                    }
                }
                intent.putExtra("mlink", true);
                context.startActivity(intent);
            }
        });


        // fivesec_mw_circles:  mLink 的 key, mLink的唯一标识,用于进行路由操作
        MLink.getInstance(context).register("fivesec_mw_circles", new MLinkCallback() {
            public void execute(Map<String, String> paramMap, Uri uri, final Context context) {
                Intent intent = new Intent(context, CircleActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                if (paramMap != null) {
                    for (Map.Entry<String, String> param : paramMap.entrySet()) {
                        intent.putExtra(param.getKey(), param.getValue());
                    }
                }
                intent.putExtra("mlink", true);
                context.startActivity(intent);
            }
        });

        if (!DeviceUtils.IsNetworkEnable()) {
            new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("您未连接网络")
                    .positiveText("退出").onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    App.GetInstance().exit();
                }
            }).show();
        } else {
            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    if (downloadId == refernece) {
                        progressDialog.dismiss();
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        Uri downloadFileUri = Uri.parse("file:///mnt/sdcard/Download/" + fileName + ".apk");
                        install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        SplashActivity.this.startActivity(install);
                    }
                }
            };
            this.registerReceiver(receiver, new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE"));
        }
        appInitPresenter = new AppInitPresenterImpl(this);
    }

    @Override
    protected void onStop() {
        this.unregisterReceiver(receiver);
        super.onStop();
    }

    @Override
    public void setupData() {
        initAppInfo();
    }
}
